package cn.itcast.consumer.web;

import cn.itcast.consumer.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    //因为线程安全 不能使用Int
//    private int conut=0;

    //这个能保证线程安全的值
    private AtomicInteger conut;

    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id){
        //拉取服务
        List<ServiceInstance> instances = discoveryClient.getInstances("USER-SERVICE");
        //利用负载均衡算法取出一个来用
//        int index=conut.getAndAdd(1) %instances.size();
//        instances.get(index);

        ServiceInstance serviceInstance = instances.get(0);
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();
        String url = String.format("http://%s:%d/user/%d", host, port, id);
//        String url="http://localhost:8081/user/"+id;
        return restTemplate.getForObject(url,User.class);
    }
}
